﻿using FineUI;
using SysManage.BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZHDJ.Core;
using ZHDJ.Core.Log;
using ZHDJ.Core.Office;
using ZHDJ.Core.Util;
using ZHDJ.Data;
using ZHDJ.Data.Models.Edu;

namespace SysManage.Module.Edu
{
    public partial class PatyEduSubjectList : BLL.PageBase
    {
        #region ViewPower

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                return "PartyEduSubjectView";
            }
        }

        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                firstLoad.Text = "1";
                LoadData();
            }
        }

        private void LoadData()
        {
            // 权限检查
            CheckPowerWithButton("PartyEduSubjectAdd", btnNew);
            CheckPowerWithButton("PartyEduSubjectDelete", btnDeleteSelected);

            BindGrid1();

            // 默认选中第一个
            Grid1.SelectedRowIndex = 0;

            string SpecialID = GetSelectedDataKeyID(Grid1);
            this.hdSpecialID.Text = SpecialID;
            this.hdSpecialName.Text = Grid1.SelectedRow.Values[1].ToString();
            //ResolveDeleteButtonForGrid(btnDeleteSelected, Grid2, "确定要从当前职称移除选中的{0}项记录吗？");
            btnNew.OnClientClick = Window1.GetShowReference("~/app/SysManage/Module/Edu/PartyEduSubjectEdit.aspx?SpecialID=" + SpecialID, "新增题目");

            // 每页记录数
            Grid2.PageSize = ConfigHelper.PageSize;
            ddlGridPageSize.SelectedValue = ConfigHelper.PageSize.ToString();

            BindGrid2();
        }

        private void BindGrid1()
        {
            IQueryable<PartyEduSpecial> q = DB.PartyEduSpecials;

            // 排列
            q = Sort<PartyEduSpecial>(q, Grid1);

            Grid1.DataSource = q;
            Grid1.DataBind();
        }

        private void BindGrid2()
        {
            string SpecialID = GetSelectedDataKeyID(Grid1);

            if (SpecialID == "-1")
            {
                Grid2.RecordCount = 0;

                Grid2.DataSource = null;
                Grid2.DataBind();
            }
            else
            {
                IQueryable<PartyEduSubject> q = DB.PartyEduSubjects;

                // 搜索内容
                string searchText = txtSubject.Text.Trim();
                if (!String.IsNullOrEmpty(searchText))
                {
                    q = q.Where(u => u.Subjectcontent.Contains(searchText) && u.SpecialID == SpecialID);
                }
                else
                {
                    q = q.Where(u => u.SpecialID == SpecialID);
                }
                // 过滤启用状态
                if (rblEnableStatus.SelectedValue != "all")
                {
                    q = q.Where(u => u.Enabled == (rblEnableStatus.SelectedValue == "enabled" ? true : false));
                }
                // 在查询添加之后，排序和分页之前获取总记录数
                Grid2.RecordCount = q.Count();

                // 排列和分页
                q = SortAndPage<PartyEduSubject>(q, Grid2);

                Grid2.DataSource = q;
                Grid2.DataBind();
            }

        }
        #endregion

        #region Events

        protected void ddlGridPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            Grid2.PageSize = Convert.ToInt32(ddlGridPageSize.SelectedValue);

            BindGrid2();
        }
        #endregion

        #region Grid1 Events

        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortDirection = e.SortDirection;
            Grid1.SortField = e.SortField;
            BindGrid1();

            // 默认选中第一个职称
            Grid1.SelectedRowIndex = 0;

            BindGrid2();
        }

        protected void Grid1_RowClick(object sender, FineUI.GridRowClickEventArgs e)
        {
            string SpecialID = GetSelectedDataKeyID(Grid1);
            this.hdSpecialID.Text = SpecialID;
            this.hdSpecialName.Text = Grid1.SelectedRow.Values[1].ToString();
            btnNew.OnClientClick = Window1.GetShowReference("~/app/SysManage/Module/Edu/PartyEduSubjectEdit.aspx?SpecialID=" + SpecialID, "新增题目");
            BindGrid2();
            if (Grid1.SelectedRowIndex != 0)
            {
                PageContext.RegisterStartupScript("removeSelectCss();");
            }
        }

        #endregion

        #region Grid2 Events

        protected void Grid2_PreDataBound(object sender, EventArgs e)
        {
            // 数据绑定之前，进行权限检查
            CheckPowerWithLinkButtonField("PartyEduSubjectDelete", Grid2, "deleteField");
        }

        protected void Grid2_Sort(object sender, GridSortEventArgs e)
        {
            Grid2.SortDirection = e.SortDirection;
            Grid2.SortField = e.SortField;
            BindGrid2();
        }

        protected void Grid2_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid2.PageIndex = e.NewPageIndex;
            BindGrid2();
        }

        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            if (!CheckPower("PartyEduSubjectDelete"))
            {
                CheckPowerFailWithAlert();
                return;
            }

            List<string> ids = GetSelectedDataKeyIDs(Grid2);
            DB.PartyEduSubjects.Where(u => ids.Contains(u.ID)).ToList().ForEach(u => DB.PartyEduSubjects.Remove(u));
            DB.SaveChanges();

            // 清空当前选中的项
            Grid2.SelectedRowIndexArray = null;

            // 重新绑定表格
            BindGrid2();
        }


        protected void Grid2_RowCommand(object sender, GridCommandEventArgs e)
        {
            object[] values = Grid2.DataKeys[e.RowIndex];
            string ID = Convert.ToString(values[0]);

            if (e.CommandName == "Delete")
            {
                //var userCount = DB.PatyEduSubjects.Count(t => t.SpecialID == patyEduSpecialId);
                //if (userCount > 0)
                //{
                //    Alert.ShowInTop("删除失败！需要先清空作用此专题的题目！");
                //    return;
                //}

                var del = DB.PartyEduSubjects.FirstOrDefault(t => t.ID == ID);
                DB.PartyEduSubjects.Remove(del);
                DB.SaveChanges();
                BindGrid2();

            }
        }
        /// <summary>
        /// 设置启用
        /// </summary>
        /// <param name="enabled"></param>
        private void SetSelectedEnableStatus(bool enabled)
        {
            // 在操作之前进行权限检查
            if (!CheckPower("PartyEduSubjectEdit"))
            {
                CheckPowerFailWithAlert();
                return;
            }

            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<string> ids = GetSelectedDataKeyIDs(Grid2);

            // 执行数据库操作
            DB.PartyEduSubjects.Where(u => ids.Contains(u.ID)).ToList().ForEach(u => u.Enabled = enabled);
            DB.SaveChanges();
            //DB.Users.Update(u => ids.Contains(u.ID), u => new User { Enabled = enabled });

            // 重新绑定表格
            BindGrid2();
        }
        protected void btnEnable_Click(object sender, EventArgs e)
        {
            SetSelectedEnableStatus(true);
        }

        protected void btnDisable_Click(object sender, EventArgs e)
        {
            SetSelectedEnableStatus(false);
        }

        protected void Window1_Close(object sender, EventArgs e)
        {
            BindGrid2();
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            string titleID = GetSelectedDataKeyID(Grid1);
            string addUrl = String.Format("~/app/box/admin/title_user_addnew.aspx?id={0}", titleID);

            PageContext.RegisterStartupScript(Window1.GetShowReference(addUrl, "添加用户到当前职称"));
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindGrid2();
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                NpoiHelper npoiHelper = new NpoiHelper();
                //1.获取从EXCEEL导入进来的数据
                DataSet ds = npoiHelper.ReadToDataSet(this.fuFile, "Sheet1", 0, 1, 19);
      
                if (ds == null)
                {
                    return;
                }
                if (Convert.ToString(ds.Tables[0].Columns[0].ColumnName).Trim() != "题目0")
                {
                    Alert.Show("导入文档格式不正确，请下载模板！");
                    return;
                }
                string strSQL = "";
                ds.Tables[0].Columns.Add("ID");
                //bool isFirst = true;

                foreach (DataRow item in ds.Tables[0].Rows)
                {
                    if (Convert.ToString(item[0]).Trim() == "")
                    {
                        continue;
                    }
                    //count++;
                    string sID = StringHelper.NewID;
                    string sCreatePeople = CurrentUser.LoginID;
                    item["ID"] = sID;
                    //题目
                    strSQL += string.Format(@"  INSERT INTO tblpartyedusubject(ID,subjectType,SpecialID,Subjectcontent,answer,isright,Enabled,createtime,createby)
VALUES('{0}',1,'{1}','{2}',1,1,1,NOW(),'{3}');", sID, this.hdSpecialID.Text, item[0], sCreatePeople);
                    int j = 1;
                    for (int i = 1; i < ds.Tables[0].Columns.Count; i = i + 2)
                    {
                        if (!string.IsNullOrEmpty(item[i].ToString()))
                        {
                            string aStr = "0";
                            if (!string.IsNullOrEmpty(item[i + 1].ToString()))
                            {
                                if (item[i + 1].ToString().Trim().Equals("是"))
                                {
                                    aStr = "1";
                                }
                            }
                            //选项
                            strSQL += string.Format(@"INSERT INTO tblpartyedusubjectoptions(ID,SubjectID,OptionsContent,IsAnswer,OrderNo)
VALUES('{0}','{1}','{2}',{3},{4});", StringHelper.NewID, sID, Convert.ToString(item[i]).Trim(), aStr, j);
                            j++;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                if (MySqlHelper.ExecuteNonQuery(strSQL) > 0)
                {
                    Alert.Show("数据导入成功!");
                }
                this.LoadData();

            }
            catch (Exception ex)
            {
                Log4netHelper.WriteLog(ex);
                Alert.Show("导入文档格式不正确，请下载模板!");
                //Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "alert('导入文档格式不正确，请下载模板！');", true);
                return;
            }
        }
        #endregion
    }
}
